package com.football.springboot.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.football.springboot.common.Constants;
import com.football.springboot.common.Result;
import com.football.springboot.common.Return;
import com.football.springboot.controller.dto.UserDTO;
import com.football.springboot.controller.dto.UserPasswordDTO;
import com.football.springboot.entity.User;
import com.football.springboot.mapper.RoleMapper;
import com.football.springboot.mapper.UserMapper;
import com.football.springboot.service.UserService;
import com.football.springboot.utils.TokenUtils;
import com.football.springboot.vo.UserQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;


@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    //用户登录
    @ApiOperation("用户登录")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result login(@RequestBody UserDTO userDto){
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        //参数错误
        if (StringUtil.isBlank(username) || StringUtil.isBlank(password)){
            return Result.error(Constants.CODE_400, "参数错误");
        }
        UserDTO dto = userService.login(userDto);
        return Result.success(dto);
    }

    //用户注册
    @ApiOperation("用户注册")
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public Result register(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StringUtil.isBlank(username) || StringUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        return Result.success(userService.register(userDTO));
    }


    //根据用户名获取User信息(个人中心中使用)
    @ApiOperation("根据用户名获取User信息")
    @RequestMapping(value = "/username/{username}",method = RequestMethod.GET)
    public Result findByUsername(@PathVariable String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return Result.success(userService.getOne(queryWrapper));
    }

    //个人信息更新
    @ApiOperation("个人信息更新")
    @RequestMapping(value = "/updateperson",method = RequestMethod.POST)
    public Result updateperson(@RequestBody User user) {
        if (user.getId() == null && user.getPassword() == null) {  // 新增用户默认密码
            user.setPassword( SecureUtil.md5("123"));
        }
        return Result.success(userService.saveOrUpdate(user));
    }


    //修改密码
    @ApiOperation("修改密码")
    @PostMapping("/updatepassword")
    public Result updatepassword(@RequestBody UserPasswordDTO userPasswordDTO) {
        userPasswordDTO.setPassword(SecureUtil.md5(userPasswordDTO.getPassword()));
        userPasswordDTO.setNewPassword(SecureUtil.md5(userPasswordDTO.getNewPassword()));
        userService.updatePassword(userPasswordDTO);
        return Result.success();
    }

    //1.查询全部用户信息
    @ApiOperation("查询全部用户信息")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public Return list(){
        //调用list方法
        List<User> users = userService.list();
        return Return.ok().put("userlist",users);
    }


    //2.添加用户
    @ApiOperation("添加用户")
    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    public Return addUser(@RequestBody User user){
        //设置默认的密码
        if (user.getPassword() == null) {  // 新增用户默认密码
            user.setPassword( SecureUtil.md5("123456"));
        }
        boolean isAdd = userService.save(user);

        if(isAdd){
            return Return.ok();
        }else{
            return Return.error();
        }
    }


    //3.根据id获取用户
    @ApiOperation("根据id获取用户")
    @RequestMapping(value = "/getUser",method = RequestMethod.GET)
    public Return getUser(@RequestParam Integer id){
        User user = userService.getById(id);
        return Return.ok().put("user",user);
    }

    //4.修改用户
    @ApiOperation("修改用户")
    @RequestMapping(value = "/updateUser",method = RequestMethod.PUT)
    public Return updateUser(@RequestBody User user){
        boolean isUpdate = userService.updateById(user);
        if (isUpdate){
            return Return.ok();
        }else {
            return Return.error();
        }
    }
    //5.条件查询加分页
    @ApiOperation("条件查询加分页")
    @RequestMapping(value = "/PageUser",method = RequestMethod.GET)
    public Return PageUser(@RequestParam long current,
                               @RequestParam long limit,
                                UserQueryVo userQueryVo){
        //创建page对象,传递当前页数current,每页记录数limit
        Page<User> page = new Page<>(current,limit);

        //构建条件 模糊查询
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        String username=userQueryVo.getUsername();
        String nickname=userQueryVo.getNickname();
        String phone=userQueryVo.getPhone();
        String email=userQueryVo.getEmail();
        String address=userQueryVo.getAddress();
//        Integer roleId=userQueryVo.getRoleId();
        //不为空再继续判断查询
        //用户名查询
        if(!StringUtils.isEmpty(username)){
            wrapper.like("username",username);
        }
        //昵称查询
        if(!StringUtils.isEmpty(nickname)){
            wrapper.like("nickname",nickname);
        }
        //手机号查询
        if(!StringUtils.isEmpty(phone)){
            wrapper.like("phone",phone);
        }
        //邮箱查询
        if(!StringUtils.isEmpty(email)){
            wrapper.like("email",email);
        }
        //地址查询
        if(!StringUtils.isEmpty(address)){
            wrapper.like("address",address);
        }

        //通过token获取用户信息
        User currentUser = TokenUtils.getCurrentUser();
        System.out.println("获取当前用户昵称:"+currentUser.getNickname());


        wrapper.orderByDesc("id");
        //调用方法实现分页查询
        Page<User> pageUsers = userService.page(page,wrapper);

        //返回结果 pageUsers是object对象，前端要用records读取数据列表
        return Return.ok().put("pageUsers", pageUsers).put("total",pageUsers.getTotal());
    }

    //6.逻辑删除用户
    @ApiOperation("逻辑删除用户")
    @RequestMapping(value = "/deleteUser/{id}",method = RequestMethod.DELETE)
    public Return deleteUser(@PathVariable("id") Integer id){
        boolean isDelete = userService.removeById(id);
        if (isDelete){
            return Return.ok();
        }else{
            return Return.error();
        }
    }

    //7.批量删除用户
    @ApiOperation("批量删除用户")
    @RequestMapping(value = "/batchDelete",method = RequestMethod.DELETE)
    public Return batchDelete(@RequestBody List<Integer> idList){
        boolean isbatchdelete = userService.removeByIds(idList);
        if (isbatchdelete){
            return Return.ok();
        }else{
            return Return.error();
        }
    }


    //8.导出接口
    @ApiOperation("导出接口")
    @RequestMapping(value = "/export",method = RequestMethod.GET)
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<User> list = userService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("avatarUrl", "头像");
        writer.addHeaderAlias("role", "角色");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    //9.导入接口
    @ApiOperation("导入接口")
    @RequestMapping(value = "/import",method = RequestMethod.POST)
    public Return imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
//        List<User> list = reader.readAll(User.class);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<User> users = CollUtil.newArrayList();
        for (List<Object> row : list) {
            User user = new User();
            user.setUsername(row.get(1).toString());
            user.setPassword(row.get(2).toString());
            user.setNickname(row.get(3).toString());
            user.setPhone(row.get(4).toString());
            user.setEmail(row.get(5).toString());
            user.setAddress(row.get(6).toString());
            user.setAvatarUrl(row.get(7).toString());
            user.setRole(row.get(8).toString());
            users.add(user);
        }

        userService.saveBatch(users);
        return Return.ok();
    }




}
